package  
{
	import engine.control.ControlCreater;
	import engine.control.MainSpaceControl;
	import engine.data.ModelLocator;
	import engine.display.AttAckMsgCacheLogic;
	import engine.display.Story.StoryLogic;
	import engine.display.newAttack.AttackLogic;
	import engine.guide.GuideManage;
	import engine.logic.AlertLogic;
	import engine.logic.ArrowGuideLogic;
	import engine.logic.FunctionGuideLogic;
	import engine.logic.ServerTimerLogic;
	import engine.logic.SnowLogic;
	import engine.logic.SpanSceneMoveLogic;
	import engine.logic.event.LogicEvent;
	import engine.logic.loading.LoadingLogic;
	import engine.logic.login.LoginCallLater;
	import engine.logic.login.LoginLogic;
	import engine.logic.login.LoginUI;
	import engine.logic.login.NormalLogin;
	import engine.logic.login.PlayCDTimerLogic;
	import engine.logic.login.UniteLogin;
	import engine.logic.login.WaitingForScene;
	import engine.logic.walk.Astar.ForbiddenAreaLogic;
	import engine.logic.walk.WalkManager;
	import engine.net.mgr.SystemSender;
	import engine.newUi.RightNoticeLogic;
	import engine.scene.PlayerLogic;
	import engine.scene.SceneChangeManager;
	import engine.sound.SoundManage;
	import engine.ui.AlertUI;
	import engine.ui.MainLogic;
	import engine.ui.MainUIManager;
	import engine.ui.UIManage;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.system.Capabilities;
	import flash.utils.getTimer;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.config.TextIni;
	import newx.com.loader.SwfLoader;
	import newx.utils.debug.IO;
	
//	[SWF(frameRate="25", width="1000", height="600", backgroundColor="0x000000")]
	public class NewxEngine extends Sprite
	{
		private		var model			:ModelLocator;		
		//public static	var	eLoadBar		:EnterLoadingUI	=	new EnterLoadingUI();
		
		private		var tRootTime:uint;		
		
		public function NewxEngine()
		{
			tRootTime	=	getTimer();
			if(stage == null)
			{
				addEventListener(Event.ADDED_TO_STAGE,init);
			}
			else
			{
				init(null);
			}
		}
		
		private function init(e:Event):void
		{
			if(StageInfo.stage == null)
			{
				throw new Error("场景对象StageInfo未初始化。");
			}
			//初始化数据模型
			model	=	ModelLocator.getInstance();
			//加载主配置文件
			model.mainIni			=	new TextIni("GameConfig.ini?r=" + getTimer(),loadServerConfig);
			
			function loadServerConfig():void
			{
				model.serverIni		=	new TextIni("ServerConfig.ini?r=" + getTimer(),initLoadingLogic);
			}
			
			function initLoadingLogic ():void
			{
				//设置CDN
				SwfLoader.CDN		=	model.mainIni.getContent("CDN","path");
				LoadingLogic.getInstance();
			}
			//设置加载进度条
			LoadingLogic._loadedCallBack =	function():void
			{
//				NxLoaderProxy.setProgress(NxLoaderProxy.proBarS+NxLoaderProxy.proBarW);
				
//				//初始化数据模型
//				model	=	ModelLocator.getInstance();
				
				//			model.dispatchEvent(new LoadingEvent(LoadingEvent.LOADING_PROCESS,{process:0,title:""}));
				
//				LoadingLogic.getInstance().setProcess(0,"");
				
				model.addEventListener(LogicEvent.RESLOADED,onLoadResComplete);

				
				//启动逻辑模块,Socket连接建立之后，开始启动逻辑
				model.addEventListener(LogicEvent.ENTERGAME_UIINIT,initLogic);
				
				onLoadedMainIniHandle();
			}
				
			//输出调试器版本等信息
			IO.traceLog("\t当前客户端游戏版本\t\t:\t"		,"vCH20111115");
			IO.traceLog("\t当前Flash播放器版本\t:\t"		+Capabilities.version);
			IO.traceLog("\t当前Flash播放器类型\t:\t"		+Capabilities.playerType);
			IO.traceLog("\t当前计算机版本\t\t:\t"		+Capabilities.os);
			IO.traceLog("\t当前系统语言\t\t:\t"		+Capabilities.language);
			IO.traceLog("\t当前屏幕分辨率\t\t:\t"		+Capabilities.screenResolutionX);
			
			StageInfo.stage.frameRate	=  12;
		}
		
		private function onLoadResComplete(e:LogicEvent):void
		{
//			NxLoaderProxy.setProgress(NxLoaderProxy.createUIS,"Loading GameRes & InitUI ...");
			trace("加载时间：",getTimer() - tRootTime);
			
			ControlCreater.initHelp();			
			//加载组件模块
			ControlCreater.getInstance();
			model.complete	=	true;
			
//			MouseManage.getInstance().initScientMouse(MouseFlag.MOUSE_DEFAULT,MouseFlag.MOUSE_BATTLE,MouseFlag.MOUSE_REPAIR,MouseFlag.MOUSE_SPLIT,MouseFlag.MOUSE_BATTLE_ACT);		//   加载鼠标样式 			
			
//			StageInfo.stage.addEventListener(MouseEvent.MOUSE_DOWN,defaultMouseDown);			//增加默认鼠标  的   点击状态
			
//			StageInfo.stage.addEventListener(MouseEvent.MOUSE_UP,defaultMouseUp);
			
//			LoginUI._loginContainer.visible = true;
			
//			NxLoaderProxy.setProgress(NxLoaderProxy.complete,"Loading GameRes...");
//			NxLoaderProxy.hide();
//			WaitingForScene.start();
			
			UIManage.getInstance().StartCreateUI(uiInitComplete);
			
			SoundManage.getInstance().playMusic( ModelLocator.getInstance().mainIni.getContent("loginMusic","path") );
			
//			checkIsLoaded();
			
//			LoginUI._backMC.visible	= true;
		}
		
		private function checkIsLoaded():void
		{
			if(LoginCallLater.AllSwfReady && SystemSender.getInstance().UICompleteFunc != null)
			{
				SystemSender.getInstance().UICompleteFunc.call();
			}
//			if(LoginCallLater.AllSwfReady && NormalLogin.getInstance().UICompleteFunc != null)
//			{
//				NormalLogin.getInstance().UICompleteFunc.call();
//			}
//			if(LoginCallLater.AllSwfReady && UniteLogin.UICompleteFunc != null)
//			{
//				UniteLogin.UICompleteFunc.call();
//			}
		}
		
		/*private function defaultMouseDown(e:MouseEvent):void
		{
			if(MouseManage.getInstance().getCursorName() != MouseFlag.MOUSE_BATTLE
			    && MouseManage.getInstance().getCursorName() != MouseFlag.MOUSE_BATTLE_ACTION)     // 鼠标不为战斗状态时（考虑战斗场景时鼠标状态）
			{
				MouseManage.getInstance().setCursor(MouseFlag.MOUST_DEFAULT_CLICK)		;
			}
		}
		
		private function defaultMouseUp(e:MouseEvent):void
		{
			if(MouseManage.getInstance().getCursorName() != MouseFlag.MOUSE_BATTLE
				&& MouseManage.getInstance().getCursorName() != MouseFlag.MOUSE_BATTLE_ACTION)
			{
				MouseManage.getInstance().setCursor(MouseFlag.MOUSE_DEFAULT)				;
			}
		}*/
		
		private function uiInitComplete():void
		{
//			LoginCallLater.setReady(LoginCallLater.UiResReady);
//			LoginCallLater.setReady(LoginCallLater.AllReady);
			LoginCallLater.AllSwfReady	=	true;
			checkIsLoaded();
			
			model.dispatchEvent(new LogicEvent(LogicEvent.INIT_COMPLETE));
			ModelLocator.getInstance().dispatchEvent(new LogicEvent(LogicEvent.ENTERGAME_UIINIT));
			
//			MarqueeUI.getInstance().Init(500,30,"",32,6,500,25);//msgBar_1
			
//			TrumpetUI.getInstance();
//			TrumpetUI.setXY(150,85);
			
//			var message:MessageUI	=	MessageUI.getInstance();
//			message.y	=	160;
//			message.show(StageInfo.mainSpace);
			
			
//			var importMessage:ImportantMessageUI	=	ImportantMessageUI.getInstance();
//			importMessage.y	=	120;
//			importMessage.show(StageInfo.mainSpace);
			
			trace("总时间消耗",getTimer() - tRootTime);
		}
		
		/**
		 * 初始化逻辑 
		 * @param e
		 * 
		 */		
		private function initLogic(e:LogicEvent):void
		{			
			//场景逻辑
			MainLogic			.getInstance();
			AttackLogic			.getInstance();
//			InterviewLogic		.getInstance();
//			RequestLogic		.getInstance();
			SoundManage			.getInstance();
//			HotKeyManage		.getInstance();
//			CollectionMsg		.getInstance();
			MainUIManager		.getInstance();
			MainSpaceControl	.getInstance();
			WalkManager			.getInstance();
			StoryLogic			.getInstance();
			AttAckMsgCacheLogic .getInstance();
			PlayerLogic			.getInstance();
			PlayCDTimerLogic	.getInstance();
			SpanSceneMoveLogic	.getInstance();
			ServerTimerLogic	.getInstance();
			FunctionGuideLogic	.getInstance();
			ArrowGuideLogic		.getInstance();
			GuideManage			.getInstance();
			RightNoticeLogic	.getInstance();
			ForbiddenAreaLogic	.getInstance();
			AlertLogic			.getInstance();
			SnowLogic			.getInstance();
//			LevelUpEffectLogic		.getInstance();
			AlertUI.Init(StageInfo.stage,"Panel_1","Button_2","textSkin");
			
//			new ActSee();
//			FreshGuideLogic.getInstance();
//			SeignioryWarGuideLogic.getInstance();
//			GamePrototypeGuide.getInstance();
//			ChatFilterLogic.getInstance();
//			
//			CustomLogic.getInstance();
			
			
			new SceneChangeManager();
		}
		

		//========================资源加载 Start  按以下顺序==============================
		//第一个加载，由init()启动
		private function onLoadedMainIniHandle():void
		{
//			NxLoaderProxy.hide();
//			//设置CDN
//			SwfLoader.CDN		=	model.mainIni.getContent("CDN","path");
			LoginCallLater.setReady(LoginCallLater.MainIniReady);
			
			LoginLogic.getInstance();
			LoginLogic.getInstance().readyCallBack=loginReadyHandler;
		}
		
		private function loginReadyHandler():void
		{
//			LoadingLogic.getInstance().setProcess(0,"Loading Config...");
			
			NxLoaderProxy.setProgress(NxLoaderProxy.configDataS,"Loading Config...");
//			NxLoaderProxy.setProgress(0,"Loading Config...");
			LoginLogic.getInstance().readyCallBack=null;
			
			LoginCallLater.setReady(LoginCallLater.LoginLogicReady);
			
			SwfLoader.StartLoad("config/AsIni/ConfigData.swf",null,onConfigLoaded,[configLoadingHandle]);
		}
		
		
		private function onConfigLoaded(val:DisplayObject,pList:Array):void
		{
//			LoadingLogic.getInstance().setProcess(100,"Loading Config...");
			
//			NxLoaderProxy.setProgress(NxLoaderProxy.uiDataS,"Loading Config...");
			
//			LoginCallLater.setReady(LoginCallLater.ConfigDataReady);
			
			StaticIni.initStaticFromObj(val);
			loadRes();
		}
		
		//====================进度侦听 Start=====================
		private function configLoadingHandle(event:Event):void
		{
			if(event == null)return;
			if(event.type == ProgressEvent.PROGRESS)
			{
				var e:ProgressEvent	=	event as ProgressEvent;
				
				var pro:Number	=	e.bytesLoaded/e.bytesTotal;
				//								model.dispatchEvent(new LoadingEvent(LoadingEvent.LOADING_PROCESS,{process:pro*100,title:"Loading Config..."}));
				
//				LoadingLogic.getInstance().setProcess(pro*100,"Loading Config...");
				
				NxLoaderProxy.setProgress(NxLoaderProxy.configDataS+NxLoaderProxy.configDataW*pro,"Loading Config...");
//				NxLoaderProxy.setProgress(pro,"Loading ConfigData");
			}
		}
		
		private function loadRes(e:Event=null):void
		{ 
			NxLoaderProxy.setProgress(80,"Loading GameRes...");
			
			var classRes		:Array	=	model.mainIni.getContent("res_swf","classRes").split(",");
			var path			:String	=	model.mainIni.getContent("res_swf","path");
			var tSize			:uint	=	classRes.length;
			var loaded			:uint	=	1;
			
			StageInfo.Clear();
			
			
			var resProgressHandle:Function	=	function(e:*):void
			{
				if(e is ProgressEvent)
				{
					var tp:Number	=	(e.bytesLoaded/e.bytesTotal) * (loaded/tSize);
					NxLoaderProxy.setProgress(NxLoaderProxy.uiDataS+NxLoaderProxy.uiDataW*tp,"Loading GameRes...");
				}
			};
			
			var loadedResHandle:Function = 
			function(val:DisplayObject,pList:Array):void
			{
				 ResManager.SaveRes(pList[1],val);
				if(loaded == tSize)
				{
					model.dispatchEvent(new LogicEvent(LogicEvent.RESLOADED));
				}
				else
				{
					loaded++;
					LoadResList(loaded - 1);
				}
			}
			
			var LoadResList:Function = function(loadCpount:uint):void
			{
				SwfLoader.StartLoad(path+classRes[loadCpount]+".swf",null,loadedResHandle,[resProgressHandle,classRes[loadCpount]]);
			}
			
			LoadResList(loaded - 1);
			
		}
		
//		private function loadRes(e:Event=null):void
//		{ 
////			LoadingLogic.getInstance().setProcess(0,"Loading GameRes & InitUI ...");
//			
//			NxLoaderProxy.setProgress(0,"Loading GameRes...");
//			
//			var classRes		:Array	=	model.mainIni.getContent("res_swf","classRes").split(",");
//			var path			:String	=	model.mainIni.getContent("res_swf","path");
//			var tSize			:uint	=	classRes.length;
//			var loaded			:uint	=	0;
//			var i				:uint;
//			
//			for(i = 0 ; i < tSize ; i ++)
//			{
//					
//				ResManager.SaveRes(
//				ResManager.loadRes(classRes[i],path+classRes[i]+".swf",function(val:DisplayObject,pList:Array):void
//				{					
//					loaded++;
//					IO.traceLog("LoadedRes:"+loaded+"/"+tSize);
//					if(loaded >= tSize)
//					{						
////						NxLoaderProxy.setProgress(NxLoaderProxy.uiDataS+NxLoaderProxy.uiDataW,"Loading GameRes & InitUI ...");
//						
//						model.dispatchEvent(new LogicEvent(LogicEvent.RESLOADED));
//						
//						
//					}
//					else
//					{
////						model.dispatchEvent(new LoadingEvent(LoadingEvent.LOADING_PROCESS,
////							{process:loaded*100/tSize,title:"Loading GameRes & InitUI ..."}));
////						
//						LoadingLogic.getInstance().setProcess(loaded/tSize,"Loading GameRes & InitUI ...");
////						
////						NxLoaderProxy.setProgress(NxLoaderProxy.uiDataS+NxLoaderProxy.uiDataW*loaded/tSize,"Loading GameRes...");
//						
//					}					
//				});
//			}
//			
//			StageInfo.Clear();
//		}
		
		//========================资源加载 End  按以下顺序==============================
		
//		private function onLoadLoginSkin(e:ProgressEvent):void
//		{
//			LoadingLogic.getInstance().setProcess(e.bytesLoaded*100/e.bytesTotal,"Loading Login Logic...");
//		}
		//=======================进度侦听 End=============================
	}
}
